<template>
  <ui-container>
    <template #extra>
      <u-button type="primary" @click="handleOnClickToEdit(-1, 'add')">
        新增
      </u-button>
    </template>
    <template #search>
      <u-form :schema="searchFormSchema" :dataSource="searchData">
        <template #footer>
          <u-button @click="handleOnClickToSearch" type="primary"
            >搜索</u-button
          >
        </template>
      </u-form>
    </template>

    <template #container>
      <a-table
        :columns="columns"
        :data-source="pageData"
        :rowKey="(record) => record.id"
        :pagination="pagination"
        :loading="loading"
        @change="handleOnChangeToLoadTable"
      >
        <template #sex="{ record }">
          <a-tag color="blue" v-if="record.sex == 1">男</a-tag>
          <a-tag color="red" v-if="record.sex == 0">女</a-tag>
        </template>
        <template #avator="{ record }">
          <a-avatar :size="36" :src="showImg(record.avator)">
            <template v-slot:icon v-if="!record.avator">{{
              record.nickName[0]
            }}</template>
          </a-avatar>
        </template>
        <template #userStatus="{ record }">
          <a-switch
            v-model:checked="record.userStatus"
            @change="(checked) => handleChangeToUpdateState(checked, record.id)"
          >
            <template #checkedChildren><check-outlined /></template>
            <template #unCheckedChildren><close-outlined /></template>
          </a-switch>
        </template>
        <template #action="{ record }">
          <u-button
            type="link"
            title="编辑"
            @click="handleOnClickToEdit(record.id, 'edit')"
            >编辑</u-button
          >
          <u-button
            v-if="record.userType == 3"
            type="link"
            title="删除"
            @click="handleOnClickToDelete(record.id)"
            >删除</u-button
          >
          <u-button
            type="link"
            title="角色授权"
            @click="handleOnClickToShowAuthorize(record)"
            >角色授权</u-button
          >
        </template>
      </a-table>
    </template>
  </ui-container>

  <a-modal
    v-model:visible="authorizeShow"
    title="角色授权"
    okText="提交"
    cancelText="关闭"
    onCancel="authorizeShow = !authorizeShow"
    @Ok="handleOnClickToAuthorizeSubmit"
  >
    <dl v-for="ruleGroup in ruleList" :key="ruleGroup.id">
      <dt>
        {{ ruleGroup.ruleGroupName }}
      </dt>
      <dd style="text-indent: 8px; margin-top: 0.5em">
        <a-checkbox-group
          v-model:value="ruleIdListData.ruleIds"
          :options="getOptions(ruleGroup.ruleVos)"
        >
          <template #label="{ value }">
            <span style="color: red">{{ value }}</span>
          </template>
        </a-checkbox-group>
      </dd>
    </dl>
  </a-modal>
</template>

<script>
import UIContainer from "basicLayoutComponent/UIContainer";
import UICLI from "components/ui-cli";

import { Table, Switch, Tag, Avatar, Modal, Checkbox } from "ant-design-vue";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons-vue";

import userIndex from "./index";

import {
  getUserPage,
  deleteUserById,
  patchUserById,
  getRuleIdListByUserId,
  saveUserRule,
} from "@/access/api/user/index";
import { getTree } from "@/access/api/role/index";

import { confirm, showMess, showImg } from "utils/Util";

export default {
  name: "AdminUserList",
  components: {
    ASwitch: Switch,
    ATag: Tag,
    CheckOutlined,
    CloseOutlined,
    ATable: Table,
    UForm: UICLI.UForm,
    UButton: UICLI.UButton,
    UiContainer: UIContainer,
    AAvatar: Avatar,
    AModal: Modal,
    ACheckbox: Checkbox,
    ACheckboxGroup: Checkbox.Group,
  },
  data() {
    return {
      searchFormSchema: userIndex.searchFormSchema,
      columns: userIndex.columns,
      pageData: [],
      pagination: {},

      loading: false,

      searchData: {
        currentIndex: 1,
        nickName: "",
        userStatus: "",
      },

      authorizeShow: false,
      ruleList: [],
      ruleIdListData: {
        ruleIds: [],
      },
    };
  },
  methods: {
    showImg(key) {
      return showImg(key);
    },
    getUserPage() {
      this.loading = true;
      /**
       * 2.后台管理员，3.注册租户 4.员工
       */
      const searchData = {
        ...this.searchData,
        // userType: 2   目前这里只展示后台员工
      };
      getUserPage(searchData).then((res) => {
        if (res) {
          this.loading = false;

          this.pageData = res.datas;

          const pagination = { ...this.pagination };
          pagination.total = res.pagination.totalCount;
          this.pagination = pagination;
        }
      });
    },
    handleOnChangeToLoadTable() {
      this.searchData.currentIndex = pagination.current;
      this.getUserPage();
    },
    handleOnClickToSearch() {
      this.getUserPage();
    },
    handleOnClickToEdit(id, _env) {
      let env = "add";
      if (_env) {
        env = _env;
      } else {
        env = -1 == id ? "add" : "edit";
      }
      this.$router.push({
        path: `/${env}/admin/user/${id}`,
      });
    },
    handleOnClickToDelete(id) {
      confirm(() => {
        deleteUserById({ id: id }).then((res) => {
          if (res) {
            showMess("删除成功");
            this.getUserPage();
          }
        });
      }, "确认要删除当前用户？");
    },
    handleChangeToUpdateState(checked, id) {
      patchUserById({
        userStatus: checked ? 1 : 0,
        id,
      }).then((res) => {
        if (res) {
          if (checked) showMess("用户已启用");
          else showMess("用户已禁用");
        }
      });
    },
    handleOnClickToAuthorizeSubmit() {
      saveUserRule(this.ruleIdListData).then((res) => {
        if (res) {
          showMess("授权成功");
          this.authorizeShow = false;
        }
      });
    },
    handleOnClickToShowAuthorize(record) {
      // 将用户ID添加到form中
      this.ruleIdListData = {
        ...this.ruleIdListData,
        userId: record.id,
      };
      // 查询所有的角色
      this.getRuleList(record.ruleGroupId);
      this.authorizeShow = true;
      // 查询当前用户所授权的角色
      this.getRuleListByUserId(record.id);
    },
    getOptions(arrs) {
      if (arrs) {
        return arrs.map((item) => {
          const _o = { label: item.ruleName, value: item.id };
          return _o;
        });
      }
      return [];
    },
    getRuleList(ruleGroupId) {
      getTree({
        // ruleGroupType: ruleGroupId,
        id: ruleGroupId,
      }).then((res) => {
        if (res) {
          this.ruleList = res;
        }
      });
    },
    getRuleListByUserId(id) {
      getRuleIdListByUserId({ id }).then((res) => {
        if (res) {
          this.ruleIdListData.ruleIds = res;
        }
      });
    },
  },
  created() {
    this.getUserPage();
  },
};
</script>

<style lang="less" scoped>
</style>